package com.wjc.train.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wjc.train.business.entity.Train;
import com.wjc.train.business.repository.TrainRepository;
import com.wjc.train.business.req.TrainQueryReq;
import com.wjc.train.business.req.TrainSaveReq;
import com.wjc.train.business.resp.TrainQueryResp;
import com.wjc.train.business.service.ITrainService;
import com.wjc.train.common.enums.LogicEnum;
import com.wjc.train.common.exception.BusinessException;
import com.wjc.train.common.untils.CopyUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 车次表 服务实现类
 * </p>
 *
 * @author Guessed
 * @since 2023-07-31
 */
@Service
@Slf4j
public class TrainServiceImpl  implements ITrainService {

    @Resource
    private TrainRepository trainRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TrainSaveReq trainSaveReq) {
        Train dbTrain =
                trainRepository.getOne(new QueryWrapper<Train>()
                        .eq("code", trainSaveReq.getCode())
                        .eq("is_deleted",LogicEnum.NOT_DELETED.getCode()));
        if(ObjectUtil.isNotEmpty(dbTrain)){
            throw new BusinessException("该车次已存在");
        }
        Train train = CopyUtil.copy(trainSaveReq, Train.class);
        trainRepository.saveOrUpdate(train);
    }

    @Override
    public IPage<TrainQueryResp> queryList(IPage<TrainQueryResp> page, TrainQueryReq trainQueryReq) {
        return trainRepository.queryList(page,trainQueryReq);
    }

    @Override
    public void delete(Long id) {
        trainRepository.getBaseMapper().deleteById(id);
    }

    @Override
    public List<TrainQueryResp> queryAll() {
        List<Train> list = trainRepository.lambdaQuery()
                                            .eq(Train::getIsDeleted, LogicEnum.NOT_DELETED.getCode())
                                            .list();
        return CopyUtil.copyList(list, TrainQueryResp.class);
    }
}
